package com.wetao.module_demo_cyh;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.orhanobut.logger.Logger;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.service.PlayService;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.view.DialogSelectVoice;
import com.wetao.lib_common.view.voicerecorder.VoiceRecorderView;
import com.wetao.module_demo_cyh.view.AudioBarChart;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;

public class VoiceRecorderActivity extends BaseActivity<EmptyCon.View, EmptyPre>
        implements EmptyCon.View {

    String[] permission=new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO};
    List<String> mPermissionList=new ArrayList<>();
    private  int mRequestCode=100;
    private boolean hasPermissionDismiss=true;
    private AlertDialog alertDialog=null;



    DialogSelectVoice voiceDialog;
    ImageView iv_close;
    TextView tv_voiceDialogtitle;
    LinearLayout lyt_luyin_pre;
    LinearLayout lyt_luyin_after;
    TextView tv_luyin_trip_pre;
    ImageView iv_huatong;
    ImageView iv_yintiao_n;
    AudioBarChart iv_yintiao_d;
    TextView tv_luyin_pre_miao;
    TextView tv_luyin_pre_trip;
    ImageView iv_laba;
    TextView tv_play_miao;
    VoiceRecorderView voiceRecorderView;
    boolean isVoiceComplete = false;
    int voiceResolveDuration;
    String voiceResolveUrl;
    int mSelectPosition;

    PlayServiceConnection mPlayServiceConnection;
    private PlayService.PlayBinder playBinder;
    private PlayService playService;


    int studentId = 1;
    int questionId = 3;
    String teacherId = "2";
    String studentName = "cyh";
    @Override
    public int getLayoutId() {
        return R.layout.demo_cyh_voice_recorder_activity;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @Override
    public void init() {
        Intent intent2 = new Intent();
        intent2.setClass(this, PlayService.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(intent2, mPlayServiceConnection, Context.BIND_AUTO_CREATE);

        requestPermission();
    }

    @Override
    protected void onStop() {
        super.onStop();
        playBinder.callStopMusic();
    }

    @Override
    protected void onDestroy() {
        if(mPlayServiceConnection != null) {
            unbindService(mPlayServiceConnection);
            mPlayServiceConnection = null;
        }

        super.onDestroy();
        if(playBinder != null) {
            playBinder = null;
        }
        if(playService != null) {
            playService.setCallback(null);
            playService = null;
        }
    }

    @OnClick({R2.id.btn_showVoiceDialog})
    public void click(View view) {
        if(view.getId() == R.id.btn_showVoiceDialog) {
            View voiceDialogView = LayoutInflater.from(this).inflate(R.layout.demo_cyh_dialog_voice_answer_detail,null);
            voiceDialog=new DialogSelectVoice(this,R.style.demo_cyh_DialogSelectVoice);
            setVoiceDialogView(voiceDialogView, voiceDialog);
            voiceDialog.setView(voiceDialogView);
            voiceDialog.show();
            voiceDialog.setCancelable(false);
            voiceDialog.setOnDismissListener(new android.content.DialogInterface.OnDismissListener(){
                @Override
                public void onDismiss(DialogInterface dialog) {
                    playBinder.callStopMusic();
                    //AppCache.getPlayService().unbindService(mPlayServiceConnection);
                }
            });
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT>=23){
            initPermission();
        }
    }
    private void initPermission() {
        mPermissionList.clear();

        for (int i=0;i<permission.length;i++){
            if (ContextCompat.checkSelfPermission(this,permission[i])!= PackageManager.PERMISSION_GRANTED){
                mPermissionList.add(permission[i]);
            }
        }
        if (mPermissionList.size()>0){
            ActivityCompat.requestPermissions(this,mPermissionList.toArray(new String[mPermissionList.size()]),mRequestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==mRequestCode){
            for (int i=0;i<grantResults.length;i++){
                if (grantResults[i]==PackageManager.PERMISSION_DENIED){
                    hasPermissionDismiss=false;
                    break;
                }
            }
            if (hasPermissionDismiss){
                Toast.makeText(this,"权限已经全部通过",Toast.LENGTH_SHORT).show();
            }else {
                showPermissionDialog();
            }
        }

    }

    private void showPermissionDialog() {
        if (alertDialog==null){
            alertDialog=new AlertDialog.Builder(this)
                    .setTitle("警告！")
                    .setMessage("已禁用权限，请手动授予")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            cancelPermissionDialog();
                            Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            cancelPermissionDialog();
                            finish();
                        }
                    }).create();
        }
        alertDialog.show();
    }

    private void cancelPermissionDialog() {
        alertDialog.dismiss();
    }


    private void setVoiceDialogView(View dialogView, DialogSelectVoice dialog) {
        isVoiceComplete = false;
        iv_close = dialogView.findViewById(R.id.close);
        tv_voiceDialogtitle = dialogView.findViewById(R.id.tv_voiceDialogtitle);
        lyt_luyin_pre = dialogView.findViewById(R.id.lyt_luyin_pre);
        lyt_luyin_after = dialogView.findViewById(R.id.lyt_luyin_after);
        tv_luyin_trip_pre = dialogView.findViewById(R.id.tv_luyin_trip_pre);
        iv_huatong = dialogView.findViewById(R.id.iv_huatong);
        iv_yintiao_n = dialogView.findViewById(R.id.iv_yintiao_n);
        iv_yintiao_d = dialogView.findViewById(R.id.iv_yintiao_d);
        iv_yintiao_d.setAnimVolum(0);
        tv_luyin_pre_miao = dialogView.findViewById(R.id.tv_luyin_pre_miao);
        tv_luyin_pre_trip = dialogView.findViewById(R.id.tv_luyin_pre_trip);
        iv_laba = dialogView.findViewById(R.id.iv_laba);
        tv_play_miao = dialogView.findViewById(R.id.tv_play_miao);
        voiceRecorderView = (VoiceRecorderView) dialogView.findViewById(R.id.voice_recorder);

        voiceDialogtitleView();
        initVoiceDialogView();
        lyt_luyin_pre.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //return true;
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (playBinder.callIsPlaying()) {
                        playBinder.callStopMusic();
                    }
                }
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceStartRecording(String trip) {
                        voiceStartView(trip);
                    }

                    @Override
                    public void onVoiceRecordFail() {
                        voiceFailView();
                    }

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        Logger.i("voiceFilePath=" +voiceFilePath + "  time = " + voiceTimeLength);
                        saveVoiceToAliyu(voiceFilePath, voiceTimeLength);
                    }

                    @Override
                    public void onVoiceMoveRecording(String trip) {
                        tv_luyin_pre_trip.setText(trip);
                    }

                    @Override
                    public void onSetVolume(int volume, int second) {
                        Logger.i("音量：" + volume);
                        Logger.i("时长：" + second);
                        tv_luyin_pre_miao.setText(second + "”");
                        iv_yintiao_d.setAnimVolum(volume);
                    }
                });
            }
        });
        LinearLayout lyt_playOrStopVoice = dialogView.findViewById(R.id.lyt_playOrStopVoice);
        lyt_playOrStopVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playBinder.callIsPlaying()) {
                    playBinder.callStopMusic();
                    iv_yintiao_d.setIsPlayRandom(false);
                } else {
                    playBinder.callSetmUrl(voiceResolveUrl);
                    iv_yintiao_d.setIsPlayRandom(true);
                }
            }
        });
        Button btn_deleteVoice = dialogView.findViewById(R.id.btn_deleteVoice);
        Button btn_resetVoice = dialogView.findViewById(R.id.btn_resetVoice);
        Button btn_sendVoice = dialogView.findViewById(R.id.btn_sendVoice);
        btn_deleteVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_deleteVoice.setBackgroundResource(R.drawable.shap_dialog_voice_6);

                View deleteView = LayoutInflater.from(VoiceRecorderActivity.this).inflate(R.layout.demo_cyh_dialog_voice_delete,null);
                TextView tv_dialog_content = deleteView.findViewById(R.id.tv_dialog_content);
                tv_dialog_content.setText("确定取消录音吗？");
                DialogSelectVoice voiceDialog=new DialogSelectVoice(VoiceRecorderActivity.this,R.style.demo_cyh_DialogSelectVoice);
                voiceDialog.setView(deleteView);
                voiceDialog.show();
                voiceDialog.setCancelable(false);
                Button btn_dialog_cancel = deleteView.findViewById(R.id.btn_dialog_cancel);
                btn_dialog_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        voiceDialog.dismiss();
                    }
                });
                Button btn_dialog_ok = deleteView.findViewById(R.id.btn_dialog_ok);
                btn_dialog_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isVoiceComplete = false;
                        voiceResolveUrl = null;
                        voiceResolveDuration = 0;
                        voiceDialog.dismiss();
                        dialog.dismiss();
                    }
                });
                voiceDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        btn_deleteVoice.setBackgroundResource(R.drawable.shap_dialog_voice_1);
                    }
                });
            }
        });
        btn_resetVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_resetVoice.setBackgroundResource(R.drawable.shap_dialog_voice_6);

                View deleteView = LayoutInflater.from(VoiceRecorderActivity.this).inflate(R.layout.demo_cyh_dialog_voice_delete,null);
                TextView tv_dialog_content = deleteView.findViewById(R.id.tv_dialog_content);
                tv_dialog_content.setText("确定重新录音吗？");
                DialogSelectVoice voiceDialog=new DialogSelectVoice(VoiceRecorderActivity.this,R.style.demo_cyh_DialogSelectVoice);
                voiceDialog.setView(deleteView);
                voiceDialog.show();
                voiceDialog.setCancelable(false);
                Button btn_dialog_cancel = deleteView.findViewById(R.id.btn_dialog_cancel);
                btn_dialog_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        voiceDialog.dismiss();
                    }
                });
                Button btn_dialog_ok = deleteView.findViewById(R.id.btn_dialog_ok);
                btn_dialog_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        voiceDialog.dismiss();
                        isVoiceComplete = false;
                        voiceResolveUrl = null;
                        voiceResolveDuration = 0;
                        voiceDialogtitleView();
                        initVoiceDialogView();
                        voiceFailView();

                    }
                });
                voiceDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        btn_resetVoice.setBackgroundResource(R.drawable.shap_dialog_voice_1);
                    }
                });
            }
        });
        btn_sendVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_sendVoice.setBackgroundResource(R.drawable.shap_dialog_voice_6);

                View deleteView = LayoutInflater.from(VoiceRecorderActivity.this).inflate(R.layout.demo_cyh_dialog_voice_delete,null);
                TextView tv_dialog_content = deleteView.findViewById(R.id.tv_dialog_content);
                tv_dialog_content.setText("确定发送给学生吗？");
                DialogSelectVoice voiceDialog=new DialogSelectVoice(VoiceRecorderActivity.this,R.style.demo_cyh_DialogSelectVoice);
                voiceDialog.setView(deleteView);
                voiceDialog.show();
                voiceDialog.setCancelable(false);
                Button btn_dialog_cancel = deleteView.findViewById(R.id.btn_dialog_cancel);
                btn_dialog_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        voiceDialog.dismiss();
                    }
                });
                Button btn_dialog_ok = deleteView.findViewById(R.id.btn_dialog_ok);
                btn_dialog_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        postSaveVoice(voiceDialog, dialog);
                    }
                });
                voiceDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        btn_sendVoice.setBackgroundResource(R.drawable.shap_dialog_voice_1);
                    }
                });
            }
        });
    }

    private void voiceDialogtitleView() {
        String strTitle = "";
        if(isVoiceComplete) {
            strTitle = "您给 " + studentName + " 的答疑语音已录完";
        } else {
            strTitle = "您正在给 " + studentName + " 录制答疑语音";
        }
        tv_voiceDialogtitle.setText(strTitle);
    }
    private void initVoiceDialogView() {
        voiceRecorderView.setIds(teacherId, studentId, questionId);
        voiceRecorderView.set120Miao(180);
        lyt_luyin_pre.setVisibility(View.GONE);
        lyt_luyin_after.setVisibility(View.GONE);
        tv_luyin_trip_pre.setVisibility(View.GONE);
        iv_close.setVisibility(View.GONE);
        if(!isVoiceComplete) {
            lyt_luyin_pre.setVisibility(View.VISIBLE);
            tv_luyin_trip_pre.setVisibility(View.VISIBLE);
            iv_close.setVisibility(View.VISIBLE);
            isShowHuatong_d_And_yintiao_d(false);
        } else {
            lyt_luyin_after.setVisibility(View.VISIBLE);
            tv_play_miao.setText(voiceResolveDuration + "”");
            isShowHuatong_d_And_yintiao_d(true);
        }
    }

    private void isShowHuatong_d_And_yintiao_d(boolean isShow) {
        if(isShow) {
            iv_huatong.setImageResource(R.drawable.huatong_d);
            iv_yintiao_d.setVisibility(View.VISIBLE);
            iv_yintiao_n.setVisibility(View.GONE);
        } else {
            iv_huatong.setImageResource(R.drawable.huatong_n);
            iv_yintiao_d.setVisibility(View.GONE);
            iv_yintiao_n.setVisibility(View.VISIBLE);
        }
    }

    private void voiceStartView(String trip) {
        if(voiceDialog == null) {
            return;
        }
        tv_luyin_pre_trip.setText(trip);
        isShowHuatong_d_And_yintiao_d(true);
        tv_luyin_pre_miao.setVisibility(View.VISIBLE);
    }
    private void voiceFailView() {
        if(voiceDialog == null) {
            return;
        }
        tv_luyin_pre_trip.setText("按住说话");
        isShowHuatong_d_And_yintiao_d(false);
        tv_luyin_pre_miao.setVisibility(View.GONE);
    }
    private void voiceSuccessView(int voiceTimeLength) {
        if(voiceDialog == null) {
            return;
        }
        isShowHuatong_d_And_yintiao_d(true);
        lyt_luyin_pre.setVisibility(View.GONE);
        lyt_luyin_after.setVisibility(View.VISIBLE);
        tv_luyin_trip_pre.setVisibility(View.GONE);
        iv_close.setVisibility(View.GONE);
        tv_luyin_pre_miao.setText(voiceTimeLength + "”");
        tv_play_miao.setText(voiceTimeLength + "”");
    }

    private void saveVoiceToAliyu(String voiceFilePath, int voiceTimeLength) {
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                final String aly_url = AliyunConfig.uploadFile(mContext, voiceFilePath, ".amr");
                if(aly_url == null) {
                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "上传语音批注失败", Toast.LENGTH_SHORT).show();
                            voiceFailView();
                        }
                    });
                    return;
                }
                Logger.i("上传阿里云语音批注地址：" + aly_url);
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        voiceResolveUrl = aly_url;
                    */
                        isVoiceComplete = true;

                        voiceResolveDuration = voiceTimeLength;
                        initVoiceDialogView();
                        voiceDialogtitleView();
                        voiceSuccessView(voiceResolveDuration);
                        /*
                    }
                });
            }
        }).start();*/

    }

    //发送语音答疑给学生
    private void postSaveVoice(DialogSelectVoice voiceDialog, DialogSelectVoice dialog) {
        /*if (!Utils.isNetworkConnected()) {
            Toast.makeText(this, "网络连接不可用", Toast.LENGTH_SHORT).show();
            if(voiceDialog != null) {
                voiceDialog.dismiss();
            }
            return;
        }
        JsonObject params = new JsonObject();
        params.addProperty("id", voiceStuInfo.data.voiceAnswers.get(mSelectPosition).id);
        params.addProperty("answerUrl", voiceResolveUrl);
        params.addProperty("answerDuration", voiceResolveDuration);
        String url = ConstantValues.getApiHost() + ApiContainer.API_VOICE_SAVE;
        Logger.i(url);
        HttpManager.post(url, params, this, new HttpManager.OnResponse<BaseBean>() {
            @Override
            public void onStart() {
                super.onStart();
                Logger.i("onStart");
            }

            @Override
            public void onCompleted() {
                Logger.i("onCompleted");
            }

            @Override
            public BaseBean analyseResult(String result) {
                Logger.i("analyseResult");
                if (JsonUtils.isGoodJson(result)) {
                    return JsonUtils.fromJson(result, BaseBean.class);
                }
                return null;
            }

            @Override
            public void onFailed(int code, String msg, String url) {
                Logger.e("失败---发送语音答疑给学生");
                if(voiceDialog != null) {
                    voiceDialog.dismiss();
                }
            }

            @Override
            public void onSuccess(BaseBean res) {
                if(res.code == 0) {
                    Logger.i("成功---发送语音答疑给学生");
                    //voiceResolveUrl = null;
                    //voiceResolveDuration = 0;
                    isVoiceComplete = false;
                    voiceDialog.dismiss();
                    dialog.dismiss();
                    getVoiceStuInfo();

                } else {
                    Logger.e("失败---发送语音答疑给学生");
                    if(voiceDialog != null) {
                        voiceDialog.dismiss();
                    }
                }
            }

        });*/
    }

    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            playService = ((PlayService.PlayBinder) binder).getService();
            Logger.i("onServiceConnected");
            playBinder = (PlayService.PlayBinder) binder;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
}
